<!doctype html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Redis," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;关于Redis的命令，主要参考Redis的官方文档。这里主要像是翻译一下，并且给出一些实用的例子。排版上，按功能重新组织了一下指令，并将比较常用的指令放在了最前面。这里的Redis版本是3.0.7，应该是目前的最新版。 &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;">
<meta name="keywords" content="Redis">
<meta property="og:type" content="article">
<meta property="og:title" content="Redis基本操作——String">
<meta property="og:url" content="https://hcldirgit.github.io/2017/09/03/Redis/9. Redis基本操作——String/index.html">
<meta property="og:site_name" content="失落的乐章">
<meta property="og:description" content="&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;关于Redis的命令，主要参考Redis的官方文档。这里主要像是翻译一下，并且给出一些实用的例子。排版上，按功能重新组织了一下指令，并将比较常用的指令放在了最前面。这里的Redis版本是3.0.7，应该是目前的最新版。 &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-09-02T17:31:15.044Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Redis基本操作——String">
<meta name="twitter:description" content="&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;关于Redis的命令，主要参考Redis的官方文档。这里主要像是翻译一下，并且给出一些实用的例子。排版上，按功能重新组织了一下指令，并将比较常用的指令放在了最前面。这里的Redis版本是3.0.7，应该是目前的最新版。 &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://hcldirgit.github.io/2017/09/03/Redis/9. Redis基本操作——String/"/>





  <title>Redis基本操作——String | 失落的乐章</title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', '85*****1', 'auto');
  ga('send', 'pageview');
</script>


  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?87980c**************99ec5e26fb5";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>











  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">失落的乐章</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">技术面前，永远都是学生。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-message">
          <a href="/message" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-external-link"></i> <br />
            
            留言
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://hcldirgit.github.io/2017/09/03/Redis/9. Redis基本操作——String/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="失落的乐章">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/0.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="失落的乐章">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Redis基本操作——String</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-09-03T02:09:22+08:00">
                2017-09-03
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;关于Redis的命令，主要参考<a href="http://redis.io/commands#string" target="_blank" rel="external">Redis的官方文档</a>。这里主要像是翻译一下，并且给出一些实用的例子。排版上，按功能重新组织了一下指令，并将比较常用的指令放在了最前面。这里的Redis版本是3.0.7，应该是目前的最新版。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;注：redis的命令（SET，GET等）是不区分大小写的（KEY和VALUE区分的），为了方便所以操作可能都是小写的。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;指令清单:</p>
<h2 id="一，SET的相关操作"><a href="#一，SET的相关操作" class="headerlink" title="一，SET的相关操作"></a>一，SET的相关操作</h2><h3 id="1-SET-key-value-EX-seconds-PX-milliseconds-NX-XX"><a href="#1-SET-key-value-EX-seconds-PX-milliseconds-NX-XX" class="headerlink" title="1.SET key value [EX seconds] [PX milliseconds] [NX|XX]"></a>1.SET key value [EX seconds] [PX milliseconds] [NX|XX]</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Set the string value of a key</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;将键key设置成指定的字符串value。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;我们知道Redis是一种key-value数据库（当然这么说可能不够严谨，因为Redis支持很多高级的数据结构）。因此所有的数据都是通过key来访问，key就是键。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;SET指令可以将字符串的value和key绑定在一起。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;如果不加额外的参数。当key中已经保存了一个值的话，这个值会被覆盖成新的值，并且忽略掉原始类型（一个key对应的不一定是一个字符串，也可以是List等其他的数据结构）；如果key不存在，那么则会在数据库中新增一个key，对应的值就是你刚刚设置的。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;例子：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">redis&gt; get name</div><div class="line">(nil)</div><div class="line">redis&gt; <span class="built_in">set</span> name miaoerduo</div><div class="line">OK</div><div class="line">redis&gt; get name</div><div class="line"><span class="string">"miaoerduo"</span></div><div class="line">redis&gt; <span class="built_in">set</span> name miao</div><div class="line">OK</div><div class="line">redis&gt; get name</div><div class="line"><span class="string">"miao"</span></div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;GET命令用于查看key对应的值，我们下面会讲到。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;第一个get，由于name这个key不存在，因此我们得到的结果是nil，也就是说空。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;之后我们设置一次，然后就get到我们的结果了。之后再设置一次，会发现结果已经被覆盖。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;这就是set命令的基本用法。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;我们看到文档的后面有一些可选的参数。下面依次来介绍：</p>
<ul>
<li><strong>EX seconds</strong>：设置key的过时时间，单位为秒。</li>
<li><strong>PX milliseconds</strong>：设置key的过期时间，单位为毫秒。</li>
</ul>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;以ex为例：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">redis&gt; <span class="built_in">set</span> name miaoerduo ex 10</div><div class="line">OK</div><div class="line">redis&gt; get name</div><div class="line"><span class="string">"miaoerduo"</span></div><div class="line">redis&gt; get name</div><div class="line">(nil)</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;我们设置了name的过期时间为10秒。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;在设置完name之后，立刻获取name的值，可以得到正确的输出。但是过了10s之后，发现只能得到一个nil。说明这个key已经被清空了。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;那么这个设置有什么作用呢？</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;我们说几个常见的应用场景：</p>
<ul>
<li><strong>验证码</strong></li>
</ul>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;我们经常在登录一些网站或是进行付款等操作的时候，都会收到一些验证码，并且说10min后失效。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;实际上就可以通过下面一条指令来实现：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">set</span> phone_num code ex 600</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;用手机号作为key，验证码作为值，超时6min。这样当你输入好验证码，提交的时候，后台就可以了先get phone_num，再比较你的输入和数据库里面存的值，从而完成身份的验证。</p>
<ul>
<li><strong>session</strong></li>
</ul>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;早前，网站通过cookie来保存用户的用户名和密码，之后出现了很多的安全隐患，因此就提出了session的机制。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;用户登陆成功之后，本地的cookie会保留一个较长的随机码，而网站后的后台则存储了这个随机码和你的用户id的对应关系。在你第二次登录的时候，cookie会传输到后台，而后台则根据你的随机码，获取你的用户信息，如果符合，则自动登录。这样，即使网站上有不法分子获取了你的cookie，也得不到你的任何信息，因为你的真实的有用的信息都存储在网站的后台。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;我们在登录邮箱的时候，通常都会有一个选项，7天内自动登录。这其实就是给后台存的session设置了一个超时。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<strong>NX</strong>：（if Not eXist）只有键key不存在的时候才会设置key的值</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<strong>XX</strong>：只有键key存在的时候才会设置key的值</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;NX通常用于实现锁机制，XX的功能，小喵暂时木有头绪。。。想到应用场景的筒子们可以留言告诉小喵，小喵看到了一定会更新的。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;举个例子：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line">redis&gt; del name</div><div class="line">(<span class="built_in">integer</span>) 0</div><div class="line">redis&gt; get name</div><div class="line">(nil)</div><div class="line">redis&gt; <span class="built_in">set</span> name miaoerduo nx</div><div class="line">OK</div><div class="line">redis&gt; <span class="built_in">set</span> name miaoerduo nx</div><div class="line">(nil)</div><div class="line">redis&gt; get name</div><div class="line"><span class="string">"miaoerduo"</span></div><div class="line">redis&gt; <span class="built_in">set</span> name miao xx</div><div class="line">OK</div><div class="line">redis&gt; get name</div><div class="line"><span class="string">"miao"</span></div><div class="line">redis&gt; del name</div><div class="line">(<span class="built_in">integer</span>) 1</div><div class="line">redis&gt; <span class="built_in">set</span> name miao xx</div><div class="line">(nil)</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;首先我们使用del指令删除了name（这个指令后面会介绍）。之后使用nx模式设置name，第一次成功了，而第二次就失败了，因为name已经存在了。之后使用xx模式修改，发现确实可以。del name之后，再使用xx模式，就失败了，因为此时的name已经不存在了。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;以上，就是set的所有的用法。</p>
<h3 id="2-SETRANGE-key-offset-value"><a href="#2-SETRANGE-key-offset-value" class="headerlink" title="2.SETRANGE key offset value"></a>2.SETRANGE key offset value</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Overwrite part of a string at key starting at the specified offset</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;这个命令可以覆盖掉key对应的string的一部分。offset表示需要覆盖的字符串的起始位置，之后会用value的值，覆盖掉原始string的对应位置的数据。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;这里有一些比较有意思的操作：如果原始key不存在，则默认为一个长度为0的字符串。如果offset超过原始string的长度，那么会在之前的string后面补充0以达到offset。如果value的长度超过了原始string后面可以覆盖的部分，则Redis内部会重新申请内存，完成数据的追加（还记得上一章的内容吗？），这时候数据库由于需要分配内存，可能会出现阻塞（需要分配的内存越大，阻塞时间越长）。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;例子：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line">redis&gt; <span class="built_in">set</span> str <span class="string">"hello world"</span></div><div class="line">OK</div><div class="line">redis&gt; setrange str 6 redis</div><div class="line">(<span class="built_in">integer</span>) 11</div><div class="line">redis&gt; get str</div><div class="line"><span class="string">"hello redis"</span></div><div class="line">redis&gt; setrange str 15 aha</div><div class="line">(<span class="built_in">integer</span>) 18</div><div class="line">redis&gt; get str</div><div class="line"><span class="string">"hello redis\x00\x00\x00\x00aha"</span></div><div class="line">redis&gt; del str</div><div class="line">(<span class="built_in">integer</span>) 1</div><div class="line">redis&gt; setrange str 5 <span class="string">"hello miao"</span></div><div class="line">(<span class="built_in">integer</span>) 15</div><div class="line">redis&gt; get str</div><div class="line"><span class="string">"\x00\x00\x00\x00\x00hello miao"</span></div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;在这个实验中，我们先新建了一个str，内容是”hello world”，之后，从位置6开始写入字符串”redis”，则得到了”hello redis”。之后我们在15的位置，写入”aha”，这是offset已经比字符串的长度要大了，则Redis会默认填充0（\x00是0的16进制表达），之后再追加字符串。最后，我们给一个不存在的key使用setrange设置了一个值，结果表现得和空字符串一样。</p>
<h3 id="3-MSET-key-value-key-value-…"><a href="#3-MSET-key-value-key-value-…" class="headerlink" title="3.MSET key value [key value …]"></a>3.MSET key value [key value …]</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Set multiple keys to multiple values</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;一次性设置多个key-value。如果key的值已存在，则会直接覆盖。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;相当与同时调用多次SET命令。不过要注意的是，这个操作是原子的。也就是说，所有的keys都一次性设置的。如果你同时运行两个MSET来设置相同的keys，那么操作的结果也只会是两次MSET中的后一次的结果，而不会是混杂的结果。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;例子：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">redis&gt; mset name1 miaoerduo name2 miao name3 love</div><div class="line">OK</div><div class="line">redis&gt; get name1</div><div class="line"><span class="string">"miaoerduo"</span></div><div class="line">redis&gt; get name2</div><div class="line"><span class="string">"miao"</span></div><div class="line">redis&gt; get name3</div><div class="line"><span class="string">"love"</span></div></pre></td></tr></table></figure>
<h3 id="4-MSETNX-key-value-key-value-…"><a href="#4-MSETNX-key-value-key-value-…" class="headerlink" title="4.MSETNX key value [key value …]"></a>4.MSETNX key value [key value …]</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Set multiple keys to multiple values, only if none of the keys exist</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;一次性设置多个key-value。如果存在任何一个key已经存在，那么这个操作都不会执行。所以，当使用MSETNX的时候，要么全部key都被修改，要么全部都不被修改。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;当然这个操作也是原子的。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">redis&gt; get name3</div><div class="line"><span class="string">"love"</span></div><div class="line">redis&gt; msetnx name3 miaoerduo name4 miao</div><div class="line">(<span class="built_in">integer</span>) 0</div><div class="line">redis&gt; get name4</div><div class="line">(nil)</div><div class="line">redis&gt; msetnx name4 miaoerduo name5 miao</div><div class="line">(<span class="built_in">integer</span>) 1</div><div class="line">redis&gt; get name4</div><div class="line"><span class="string">"miaoerduo"</span></div><div class="line">redis&gt; get name5</div><div class="line"><span class="string">"miao"</span></div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;当name3已经存在的时候，我们设置name3和name4，发现，连name4都没有创建。当设置name4和name5的时候，由于这两个key之前都不存在，因此设置成功了。</p>
<h3 id="5-SETEX-key-seconds-value"><a href="#5-SETEX-key-seconds-value" class="headerlink" title="5.SETEX key seconds value"></a>5.SETEX key seconds value</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Set the value and expiration of a key</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;设置key的值和超时。和前面的set key value ex seconds一样。</p>
<h3 id="6-PSETEX-key-milliseconds-value"><a href="#6-PSETEX-key-milliseconds-value" class="headerlink" title="6.PSETEX key milliseconds value"></a>6.PSETEX key milliseconds value</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Set the value and expiration in milliseconds of a key</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;设置key的值和超时。和前面的set key value px milliseconds一样。</p>
<h3 id="7-SETNX-key-value"><a href="#7-SETNX-key-value" class="headerlink" title="7.SETNX key value"></a>7.SETNX key value</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Set the value of a key, only if the key does not exist</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;当key不存在的时候，设置key的值。和set key value nx一样。</p>
<h2 id="二、GET的相关操作"><a href="#二、GET的相关操作" class="headerlink" title="二、GET的相关操作"></a>二、GET的相关操作</h2><h3 id="1-GET-key"><a href="#1-GET-key" class="headerlink" title="1.GET key"></a>1.GET key</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Get the value of a key</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;根据给定的key，获取value值。这个操作，我们之前已经使用了很多次。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;如果key不存在，会返回nil。如果key对应的值不是string(List，Set等)，则会报错，因为GET只能处理string类型的value。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;演示如下：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">redis&gt; get name</div><div class="line">(nil)</div><div class="line">redis&gt; <span class="built_in">set</span> name <span class="string">"miaoerduo"</span></div><div class="line">OK</div><div class="line">redis&gt; get name</div><div class="line"><span class="string">"miaoerduo"</span></div><div class="line">redis&gt; lpush arr 1 2 3 4 5</div><div class="line">(<span class="built_in">integer</span>) 5</div><div class="line">redis&gt; get arr</div><div class="line">(error) WRONGTYPE Operation against a key holding the wrong kind of value</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;注意，lpush是List部分的内容，arr的值是一个List的结构。这里只需要知道key不是  string类型的时候，get的时候就会报错。</p>
<h3 id="2-MGET-key-key-…"><a href="#2-MGET-key-key-…" class="headerlink" title="2.MGET key [key …]"></a>2.MGET key [key …]</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Get the values of all the given keys</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;还记得我们之前可以同时设置多个key-value吗？其实我们也可以一次性获取多个key的值。如果key不存在，则对应的地方返回nil。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;那么一次性获取多个值和单独一次一次GET有什么区别呢？</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;主要有两点，原子操作和查询效率。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;比如博客上会统计评论数和访问数。如果我们依次读取这两部分的值，那么可能得到的两个值并不是同一时刻的。而如果使用MGET，则得到的一定是同一时刻的。这就是原子操作的威力（注，官方文档只介绍了SET和GET的操作是原子的，并没有说MGET是不是，这里小喵果断的说MGET是原子操作也是不合理的。但考虑到使用MGET的时候，是把查询指令一次性传输到后台来执行，所以应该原子操作。无论如何，在上面的例子中，使用MGET总是比两次GET要合理的）。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;另外，如果数据库的查询，都分为三个过程，传输查询指令，执行指令，输出结果。<br>如果分多次GET的话，在传输指令和输出结果的这两个部分就要重复很多次，效率大打折扣。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;分多次查询，需要传输的指令数目，也不会比单次多很多，为什么一定会影响效率呢？</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;其实不然，传输数据需要很多的准备工作，不仅仅是数据的具体传输，有时候需要考虑连接的创建和关闭、设置锁等的开销。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">redis&gt; <span class="built_in">set</span> key1 a</div><div class="line">OK</div><div class="line">redis&gt; <span class="built_in">set</span> key2 b</div><div class="line">OK</div><div class="line">redis&gt; mget key1 key2 key3</div><div class="line">1) <span class="string">"a"</span></div><div class="line">2) <span class="string">"b"</span></div><div class="line">3) (nil)</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;我们只创建了key1和key2，使用MGET获取的时候，由于没有key3，对应的位置返回了nil。</p>
<h3 id="3-GETRANGE-key-start-end"><a href="#3-GETRANGE-key-start-end" class="headerlink" title="3.GETRANGE key start end"></a>3.GETRANGE key start end</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Get a substring of the string stored at a key</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;该指令只要用于获取字符串的字串，在Redis2.0版本之前，叫做SUBSTR。strat和end是字串的起始和结束的位置，可以用负数来表示距离string尾部的未知的下标。-1是最后一个字符，-2是底数第二个字符。这个表达方式和Python的获取list的子list非常相似。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;需要注意的有两点：</p>
<ul>
<li>字串包括了start和end这两个位置的字符。在Python中是不包含end的。</li>
<li>当给出的start和end超出了string的范围时，指令只会返回在string内的结果。</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">redis&gt; <span class="built_in">set</span> str <span class="string">"hello world"</span></div><div class="line">OK</div><div class="line">redis&gt; getrange str 6 -1</div><div class="line"><span class="string">"world"</span></div><div class="line">redis&gt; getrange str -5 -1</div><div class="line"><span class="string">"world"</span></div><div class="line">redis&gt; getrange str 0 4</div><div class="line"><span class="string">"hello"</span></div><div class="line">redis&gt; getrange str 0 100</div><div class="line"><span class="string">"hello world"</span></div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;上述例子是几种情况下的输出。</p>
<h3 id="4-GETSET-key-value"><a href="#4-GETSET-key-value" class="headerlink" title="4.GETSET key value"></a>4.GETSET key value</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Set the string value of a key and return its old value</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;设置key的值，并返回之前的值。如果之前key的值不是string，则会报错。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;这个指令相当于先GET，再SET。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;这个指令可以用来配合INCR指令一起使用支持重置的技术功能（INCR我们后面会讲到）。先设置count为0，每次INCR使得count加1。等到需要获取计数的时候，使用GETSET count 0，就能获取计数的值，并且把计数器重置了。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">redis&gt; <span class="built_in">set</span> str <span class="string">"hello"</span></div><div class="line">OK</div><div class="line">redis&gt; getset str <span class="string">"world"</span></div><div class="line"><span class="string">"hello"</span></div><div class="line">redis&gt; get str</div><div class="line"><span class="string">"world"</span></div></pre></td></tr></table></figure>
<ul>
<li>第一行设置str为”hello”</li>
<li>第二行获取了str原先的值，并把str设置成”world”。</li>
<li>第三行GET的时候，就是修改之后的值了。</li>
</ul>
<h2 id="三、string的修改操作"><a href="#三、string的修改操作" class="headerlink" title="三、string的修改操作"></a>三、string的修改操作</h2><h3 id="1-STRLEN-key"><a href="#1-STRLEN-key" class="headerlink" title="1.STRLEN key"></a>1.STRLEN key</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Get the length of the value stored in a key</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;返回key对应的string的长度，如果key对应的不是string，则报错。如果key不存在，则返回0（还是把key对应的看成空字符串）。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">redis&gt; <span class="built_in">set</span> str <span class="string">"hello world"</span></div><div class="line">OK</div><div class="line">redis&gt; strlen str</div><div class="line">(<span class="built_in">integer</span>) 11</div><div class="line">redis&gt; get nokey</div><div class="line">(nil)</div><div class="line">redis&gt; strlen nokey</div><div class="line">(<span class="built_in">integer</span>) 0</div></pre></td></tr></table></figure>
<h3 id="2-APPEND-key-value"><a href="#2-APPEND-key-value" class="headerlink" title="2.APPEND key value"></a>2.APPEND key value</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Append a value to a key</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;如果key已经存在，且值为string，则将value追加到值的后面，如果key不存在，则会创建一个空的字符串的key，然后执行追加操作。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">redis&gt; <span class="built_in">set</span> str <span class="string">"hello"</span></div><div class="line">OK</div><div class="line">redis&gt; append str <span class="string">" world"</span></div><div class="line">(<span class="built_in">integer</span>) 11</div><div class="line">redis&gt; get str</div><div class="line"><span class="string">"hello world"</span></div><div class="line">redis&gt; del str</div><div class="line">(<span class="built_in">integer</span>) 1</div><div class="line">redis&gt; append str <span class="string">"hello"</span></div><div class="line">(<span class="built_in">integer</span>) 5</div><div class="line">redis&gt; get str</div><div class="line"><span class="string">"hello"</span></div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;这个例子中，我们先向已有值的str中append了一个字符串。然后向不存在的key，也添加了字符串。</p>
<h3 id="3-INCR-key"><a href="#3-INCR-key" class="headerlink" title="3.INCR key"></a>3.INCR key</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Increment the integer value of a key by one</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;对存储在key的整数值进行原子的加1操作。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;如果key不存在，则会设置默认值0，再加1。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;如果key存在，但是存储的值不是字符串，或者存储的字符串不能表示整数，则执行该操作时，会报错。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;这个操作仅限于64位的有符号的整型数据。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;比较有意思的是，虽然这个key存储的值是个字符串，但是该操作的效果和对相应的数字进行操作一样。而且，Redis中，在存储这类字符串的时候，底层上其实存储的就是一个整数，因此不存在存储上的浪费。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line">redis&gt; <span class="built_in">set</span> count 0</div><div class="line">OK</div><div class="line">redis&gt; incr count</div><div class="line">(<span class="built_in">integer</span>) 1</div><div class="line">redis&gt; incr count</div><div class="line">(<span class="built_in">integer</span>) 2</div><div class="line">redis&gt; del count</div><div class="line">(<span class="built_in">integer</span>) 1</div><div class="line">redis&gt; get count</div><div class="line">(nil)</div><div class="line">redis&gt; incr count</div><div class="line">(<span class="built_in">integer</span>) 1</div><div class="line">redis&gt; incr count</div><div class="line">(<span class="built_in">integer</span>) 2</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;值得注意的是，该操作是原子操作，即使有多个请求传输到Redis，count执行的结果都不会错误，所以我们可以大胆放心的用这个功能实现多线程的计数功能。</p>
<h3 id="4-DECR-key"><a href="#4-DECR-key" class="headerlink" title="4.DECR key"></a>4.DECR key</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Decrement the integer value of a key by one</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;对存储在key的整数值进行原子的减1操作。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;注意事项和INCR一样。</p>
<h3 id="5-INCRBY-key-increment"><a href="#5-INCRBY-key-increment" class="headerlink" title="5.INCRBY key increment"></a>5.INCRBY key increment</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Increment the integer value of a key by the given amount</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;对存储在key的整数值进行原子的加操作，加increment。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;如果key不存在，操作之前，key就会被置为0。如果key的value类型错误或者是个不能表示成数字的字符串，就返回错误。这个操作最多支持64位有符号的整型数字。基本上和INCR一样。</p>
<h3 id="6-DECRBY-key-decrement"><a href="#6-DECRBY-key-decrement" class="headerlink" title="6.DECRBY key decrement"></a>6.DECRBY key decrement</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Decrement the integer value of a key by the given number</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;对存储在key的整数值进行原子的减操作，减increment。</p>
<h3 id="7-INCRBYFLOAT-key-increment"><a href="#7-INCRBYFLOAT-key-increment" class="headerlink" title="7.INCRBYFLOAT key increment"></a>7.INCRBYFLOAT key increment</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Increment the float value of a key by the given amount</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;对存储造key中的浮点数进行原子的加操作，加increment。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;如果key不存在，操作之前，key就会被置为0。如果key的value类型错误或者是个不能表示成浮点数的字符串，就返回错误。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;我们并没有DECRBYFLOAT这个操作，因此想要实现减操作，只需要把increment设成负的就可以。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">redis&gt; <span class="built_in">set</span> a 1.5</div><div class="line">OK</div><div class="line">redis&gt; incrbyfloat a 10.1</div><div class="line"><span class="string">"11.6"</span></div><div class="line">redis&gt; incrbyfloat a 10.1</div><div class="line"><span class="string">"21.7"</span></div><div class="line">redis&gt; incrbyfloat a -10.1</div><div class="line"><span class="string">"11.6"</span></div><div class="line">redis&gt; incrbyfloat a -1.5e2</div><div class="line"><span class="string">"-138.39999999999999999"</span></div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;浮点数可以用一般的小数和科学计数法表示。</p>
<h2 id="四、二进制操作"><a href="#四、二进制操作" class="headerlink" title="四、二进制操作"></a>四、二进制操作</h2><h3 id="1-SETBIT-key-offset-value"><a href="#1-SETBIT-key-offset-value" class="headerlink" title="1.SETBIT key offset value"></a>1.SETBIT key offset value</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Sets or clears the bit at offset in the string value stored at key</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;设置或者清空key的value(字符串)在offset处的bit值。这里将string看成由bit组成的数组。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;指定位置的bit可以被设置，或者被清空，这个由value（只能是0或者1）来决定。当key不存在的时候，就创建一个新的字符串value。要确保这个字符串足够长到在offset处有bit值。参数offset需要大于等于0，并且小于2^32(限制bitmap大小为512)。当key对应的字符串增大的时候，新增的部分bit值都是设置为0。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;该操作返回value原来的offset位置的bit值。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">redis&gt; setbit a 0 1</div><div class="line">(<span class="built_in">integer</span>) 0</div><div class="line">redis&gt; setbit a 1 1</div><div class="line">(<span class="built_in">integer</span>) 0</div><div class="line">redis&gt; setbit a 2 1</div><div class="line">(<span class="built_in">integer</span>) 0</div><div class="line">redis&gt; setbit a 3 1</div><div class="line">(<span class="built_in">integer</span>) 0</div><div class="line">redis&gt; get a</div><div class="line"><span class="string">"\xf0"</span></div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;a最开始不存在，使用setbit操作，将a的前4位都设置成1。最终就得到了\xf0，这是16进制表示的结果，前4位都是1，其他都是0。</p>
<h3 id="2-GETBIT-key-offset"><a href="#2-GETBIT-key-offset" class="headerlink" title="2.GETBIT key offset"></a>2.GETBIT key offset</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Returns the bit value at offset in the string value stored at key</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;获取key对应的string在offset处的bit值。当offset超出了字符串长度的时候，这个字符串就被假定为由0比特填充的连续空间。当key不存在的时候，它就认为是一个空字符串，所以offset总是超出范围，然后value也被认为是由0比特填充的连续空间。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">redis&gt; setbit a 7 1</div><div class="line">(<span class="built_in">integer</span>) 0</div><div class="line">redis&gt; getbit a 0</div><div class="line">(<span class="built_in">integer</span>) 0</div><div class="line">redis&gt; getbit a 7</div><div class="line">(<span class="built_in">integer</span>) 1</div><div class="line">redis&gt; getbit a 100</div><div class="line">(<span class="built_in">integer</span>) 0</div></pre></td></tr></table></figure>
<h3 id="3-BITCOUNT-key-start-end"><a href="#3-BITCOUNT-key-start-end" class="headerlink" title="3.BITCOUNT key [start end]"></a>3.BITCOUNT key [start end]</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Count set bits in a string</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;统计key的string的二进制中1的个数。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;start和end分别表示string的起始和结束位置，含义和GETRANGE中一样。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">redis&gt; setbit mykey 0 1</div><div class="line">(<span class="built_in">integer</span>) 0</div><div class="line">redis&gt; setbit mykey 10 1</div><div class="line">(<span class="built_in">integer</span>) 0</div><div class="line">redis&gt; setbit mykey 5 1</div><div class="line">(<span class="built_in">integer</span>) 0</div><div class="line">redis&gt; bitcount mykey</div><div class="line">(<span class="built_in">integer</span>) 3</div></pre></td></tr></table></figure>
<h3 id="4-BITOP-operation-destkey-key-key-…"><a href="#4-BITOP-operation-destkey-key-key-…" class="headerlink" title="4.BITOP operation destkey key [key …]"></a>4.BITOP operation destkey key [key …]</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Perform bitwise operations between strings</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;对string进行bit级别的操作。具体操作有4种。AND，OR，XOR，NOT。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;用法如下：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">BITOP AND destkey srckey1 srckey2 srckey3 … srckeyN</div><div class="line">BITOP OR destkey srckey1 srckey2 srckey3 … srckeyN</div><div class="line">BITOP XOR destkey srckey1 srckey2 srckey3 … srckeyN</div><div class="line">BITOP NOT destkey srckey</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;NOT操作后面只有一个目标key和srckey，是因为NOT操作是一元的。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;对于AND，OR和XOR操作，Redis会将srckey1，srckey2，…，srckeyN这些字符串对位进行相关操作，之后将结果存入destkey中。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;如果srckey的length不相等的话，Redis内部会将短的字符串补齐，并填充上0。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div></pre></td><td class="code"><pre><div class="line">redis&gt; <span class="built_in">set</span> key1 <span class="string">"\xf0\xf0"</span></div><div class="line">OK</div><div class="line">redis&gt; <span class="built_in">set</span> key2 <span class="string">"\x0f\x0f"</span></div><div class="line">OK</div><div class="line">redis&gt; <span class="built_in">set</span> key3 <span class="string">"\xff\xff"</span></div><div class="line">OK</div><div class="line">redis&gt; bitop and destkey key1 key2 key3</div><div class="line">(<span class="built_in">integer</span>) 2</div><div class="line">redis&gt; get destkey</div><div class="line"><span class="string">"\x00\x00"</span></div><div class="line">redis&gt; bitop or destkey key1 key2 key3</div><div class="line">(<span class="built_in">integer</span>) 2</div><div class="line">redis&gt; get destkey</div><div class="line"><span class="string">"\xff\xff"</span></div><div class="line">redis&gt; bitop xor destkey key1 key2 key3</div><div class="line">(<span class="built_in">integer</span>) 2</div><div class="line">redis&gt; get destkey</div><div class="line"><span class="string">"\x00\x00"</span></div><div class="line">redis&gt; bitop not destkey key1</div><div class="line">(<span class="built_in">integer</span>) 2</div><div class="line">redis&gt; get destkey</div><div class="line"><span class="string">"\x0f\x0f"</span></div></pre></td></tr></table></figure>
<h3 id="5-BITPOS-key-bit-start-end"><a href="#5-BITPOS-key-bit-start-end" class="headerlink" title="5.BITPOS key bit [start] [end]"></a>5.BITPOS key bit [start] [end]</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Find first bit set or clear in a string</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;返回string的二进制中第一个0或1的位置。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;这里将string看成一个有许多bit组成的数组。其中start和end表示string的一个间隔，如果指定了start和end，则BITPOS只会查询这个区间。注意，start和end表示的字符的位置，不是bit的位置。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;即使指定了start和end，BITPOS这个操作也只会这个目标bit的绝对地址。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;有几点需要注意：</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;在没有指定查询区间或只指定start的时候，查询bit位为0的位置时，如果string中没有该位，则会返回string的bit位的总数。比如在\xff\xff\xff直接查询bit为0的位置，Redis默认该字符串后面都是0，因此，返回的结果就是12（下标从0开始数的）。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;如果指定了查询区间，无论查询0或是1，在没查询到的时候只会返回-1。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;在没有指定查询区间时，查询bit位为1的位置时，如果string中没有该位，则会返回-1，表示未查询到。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line">redis&gt; <span class="built_in">set</span> bits <span class="string">"\x00\xff\x00\xff"</span></div><div class="line">OK</div><div class="line">redis&gt; strlen bits</div><div class="line">(<span class="built_in">integer</span>) 4</div><div class="line">redis&gt; bitpos bits 0</div><div class="line">(<span class="built_in">integer</span>) 0</div><div class="line">redis&gt; bitpos bits 1</div><div class="line">(<span class="built_in">integer</span>) 8</div><div class="line">redis&gt; bitpos bits 0 1 </div><div class="line">(<span class="built_in">integer</span>) 16</div><div class="line">redis&gt; bitpos bits 0 1 -1</div><div class="line">(<span class="built_in">integer</span>) 16</div><div class="line">redis&gt; bitpos bits 1 1 -1</div><div class="line">(<span class="built_in">integer</span>) 8</div><div class="line">redis&gt; bitpos bits 0 3</div><div class="line">(<span class="built_in">integer</span>) 32</div><div class="line">redis&gt; bitpos bits 0 3 3</div><div class="line">(<span class="built_in">integer</span>) -1</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;看上面的例子，bits的初始设置的二进制表示为：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">00000000 11111111 00000000 11111111</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;直接获取0（bitpos bits 0）的位置为0，获取1（bitpos bits 1）的位置为8。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;指定开始位置为1（start = 1）的时候，0第一次出现（bitpos bits 1）的位置为 16。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;指定起始位置为3（start = 3）的时候，0第一次出现（bitpos bits 0 3）的位置为32。这是因为Redis在查询字符串的时候查询到了字符串的末尾，之后默认末尾的后面都是 0，因此得到了32这的个位置。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;最后，当指定必须在第3个字节（从0开始数）查询0的时候，由于查不到0，因此只返回了-1。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Redis/" rel="tag"># Redis</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/09/03/Redis/8. Redis 起步/" rel="next" title="Redis 起步">
                <i class="fa fa-chevron-left"></i> Redis 起步
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/09/03/Saltstack/1. Saltstack 安装配置/" rel="prev" title="resin安装与配置">
                resin安装与配置 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/0.png"
               alt="失落的乐章" />
          <p class="site-author-name" itemprop="name">失落的乐章</p>
           
              <p class="site-description motion-element" itemprop="description">失落的乐章的Blog</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/">
                <span class="site-state-item-count">627</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">38</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/hcldirgit" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#一，SET的相关操作"><span class="nav-number">1.</span> <span class="nav-text">一，SET的相关操作</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-SET-key-value-EX-seconds-PX-milliseconds-NX-XX"><span class="nav-number">1.1.</span> <span class="nav-text">1.SET key value [EX seconds] [PX milliseconds] [NX|XX]</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-SETRANGE-key-offset-value"><span class="nav-number">1.2.</span> <span class="nav-text">2.SETRANGE key offset value</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-MSET-key-value-key-value-…"><span class="nav-number">1.3.</span> <span class="nav-text">3.MSET key value [key value …]</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-MSETNX-key-value-key-value-…"><span class="nav-number">1.4.</span> <span class="nav-text">4.MSETNX key value [key value …]</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-SETEX-key-seconds-value"><span class="nav-number">1.5.</span> <span class="nav-text">5.SETEX key seconds value</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-PSETEX-key-milliseconds-value"><span class="nav-number">1.6.</span> <span class="nav-text">6.PSETEX key milliseconds value</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#7-SETNX-key-value"><span class="nav-number">1.7.</span> <span class="nav-text">7.SETNX key value</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、GET的相关操作"><span class="nav-number">2.</span> <span class="nav-text">二、GET的相关操作</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-GET-key"><span class="nav-number">2.1.</span> <span class="nav-text">1.GET key</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-MGET-key-key-…"><span class="nav-number">2.2.</span> <span class="nav-text">2.MGET key [key …]</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-GETRANGE-key-start-end"><span class="nav-number">2.3.</span> <span class="nav-text">3.GETRANGE key start end</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-GETSET-key-value"><span class="nav-number">2.4.</span> <span class="nav-text">4.GETSET key value</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三、string的修改操作"><span class="nav-number">3.</span> <span class="nav-text">三、string的修改操作</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-STRLEN-key"><span class="nav-number">3.1.</span> <span class="nav-text">1.STRLEN key</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-APPEND-key-value"><span class="nav-number">3.2.</span> <span class="nav-text">2.APPEND key value</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-INCR-key"><span class="nav-number">3.3.</span> <span class="nav-text">3.INCR key</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-DECR-key"><span class="nav-number">3.4.</span> <span class="nav-text">4.DECR key</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-INCRBY-key-increment"><span class="nav-number">3.5.</span> <span class="nav-text">5.INCRBY key increment</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-DECRBY-key-decrement"><span class="nav-number">3.6.</span> <span class="nav-text">6.DECRBY key decrement</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#7-INCRBYFLOAT-key-increment"><span class="nav-number">3.7.</span> <span class="nav-text">7.INCRBYFLOAT key increment</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#四、二进制操作"><span class="nav-number">4.</span> <span class="nav-text">四、二进制操作</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-SETBIT-key-offset-value"><span class="nav-number">4.1.</span> <span class="nav-text">1.SETBIT key offset value</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-GETBIT-key-offset"><span class="nav-number">4.2.</span> <span class="nav-text">2.GETBIT key offset</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-BITCOUNT-key-start-end"><span class="nav-number">4.3.</span> <span class="nav-text">3.BITCOUNT key [start end]</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-BITOP-operation-destkey-key-key-…"><span class="nav-number">4.4.</span> <span class="nav-text">4.BITOP operation destkey key [key …]</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-BITPOS-key-bit-start-end"><span class="nav-number">4.5.</span> <span class="nav-text">5.BITPOS key bit [start] [end]</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">失落的乐章</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Muse
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  






  





  

  

  

  

  

  

</body>
</html>
